﻿using System;
using System.Web.Mvc;
using NHibernate;
using music.domain.Services;

namespace music.web.Controllers
{
	public abstract class BaseController : Controller
	{
		protected override void OnAuthorization(AuthorizationContext filterContext)
		{
			if (CurrentUserId == default(Guid))
			{
				using (var session = OpenSession())
				{
					CurrentUserId = AccountService.InitCurrentUser(session, User.Identity.Name);
				}
			}

			base.OnAuthorization(filterContext);
		}

		public Guid CurrentUserId
		{
			get
			{
				return Session["CurrentUserId"] is Guid 
					? (Guid)Session["CurrentUserId"] 
					: default(Guid);
			}
			private set { Session["CurrentUserId"] = value; }
		}

		public ISession OpenSession()
		{
			return MusicApplication.Container.Resolve<ISessionFactory>().OpenSession();
		}
	}
}
